<?php

namespace LRP;

/**
 * Class Lock
 *
 * PHP Version > 7.0
 *
 * @package LRP
 * @author  Jon
 * @link    https://gitee.com/joncc/long-running-processor
 */
class FileLock
{
    private static $lock_file_arr = [];

    private $type = LOCK_EX | LOCK_NB;

    private $file;

    /**
     * FileLock constructor.
     *
     * @param string $lock_file
     */
    public function __construct(string $lock_file = '')
    {
        $this->file = $lock_file;
    }

    /**
     * @param int $lock_type
     */
    public function setType(int $lock_type)
    {
        $this->type = $lock_type;
    }

    /**
     * @return bool
     */
    public function isLock()
    {
        $key = md5($this->file);
        self::$lock_file_arr[$key] = fopen($this->file, 'a+');
        if (self::$lock_file_arr[$key] === false) {
            unset(self::$lock_file_arr[$key]);
            return false;
        }

        if (flock(self::$lock_file_arr[$key], $this->type)) {

            ftruncate(self::$lock_file_arr[$key], 0);
            fwrite(self::$lock_file_arr[$key], getmypid());
            fflush(self::$lock_file_arr[$key]);

            return true;
        }

        fclose(self::$lock_file_arr[$key]);
        return false;
    }
}